package com.atguigu.service_edu.listener;

import com.alibaba.excel.context.AnalysisContext;
import com.alibaba.excel.event.AnalysisEventListener;
import com.atguigu.service_edu.entity.EduSubject;
import com.atguigu.service_edu.entity.excel.SubjectData;
import com.atguigu.service_edu.service.EduSubjectService;
import com.atguigu.servicebase.exception.GuliException;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import org.springframework.stereotype.Component;


public class SubjectExcelListener extends AnalysisEventListener<SubjectData> {



    public EduSubjectService eduSubjectService;

    public SubjectExcelListener() { }
    public SubjectExcelListener(EduSubjectService eduSubjectService) {
        this.eduSubjectService = eduSubjectService;
    }

    //每次读取一行执行一次
    @Override
    public void invoke(SubjectData subjectData, AnalysisContext analysisContext) {
        if(subjectData == null){
            throw new GuliException(20001,"文件数据为空");
        }

        //读取Excel内容:一行一行读取
        //添加一级分类
        EduSubject eduSubject = this.existOneSubject(this.eduSubjectService, subjectData.getOneSubjectName());
        if(eduSubject == null){
            eduSubject = new EduSubject();
            eduSubject.setParentId("0");
            eduSubject.setTitle(subjectData.getOneSubjectName());
            eduSubjectService.save(eduSubject);
        }
        //获取一级分类Id
        String pid = eduSubject.getId();
        //添加二级分类
        EduSubject eduSubjectTwo = this.existTwoSuject(this.eduSubjectService,subjectData.getTwoSubjectName(),pid);
        if(eduSubjectTwo == null){
            eduSubjectTwo = new EduSubject();
            eduSubjectTwo.setParentId(pid);
            eduSubjectTwo.setTitle(subjectData.getTwoSubjectName());
            eduSubjectService.save(eduSubjectTwo);
        }
    }
    //判断一级分类不能重复添加
    private EduSubject existOneSubject(EduSubjectService service,String name){
        QueryWrapper<EduSubject> wrapper = new QueryWrapper<>();
        wrapper.eq("title",name);
        wrapper.eq("parent_id","0");
        EduSubject eduSubject = service.getOne(wrapper);
        return eduSubject;
    }
    //判断二级分类不能重复添加
    private EduSubject existTwoSuject(EduSubjectService service,String name,String pid){
        QueryWrapper<EduSubject> wrapper = new QueryWrapper<>();
        wrapper.eq("title",name);
        wrapper.eq("parent_id",pid);
        EduSubject eduSubject = service.getOne(wrapper);
        return eduSubject;
    }

    @Override
    public void doAfterAllAnalysed(AnalysisContext analysisContext) {

    }
}
